package org.zhu.back.mysqlBackUp;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

/**
 * Created by yingzhi zhu on 2017/9/14.
 * 数据库备份处理
 */
public class BackUtil {

    private String mysqlHome = "";
    private String backCommand = "mysqldump -h %s -u%s -p%s %s";

    public BackUtil setMysqlHome(String mysqlHome){
        this.mysqlHome = mysqlHome;
        return this;
    }

    public BackUtil setBackCommand(String host,String username,String password,String dbName){
        this.backCommand = mysqlHome+String.format(backCommand, host,username,password,dbName);
        return this;
    }

    public String backUp(String dir,String fileName) throws IOException {
        System.out.println(backCommand);
        Runtime runtime = Runtime.getRuntime(); //获取jvm的运行环境
        Process child = runtime.exec(backCommand);//调用程序
        InputStream in = child.getInputStream();//创建输入流接收目标程序的输入
        InputStreamReader reader = new InputStreamReader(in,"utf-8");//编码转化
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuffer sb = new StringBuffer();
        String tempStr = "";
        while ((tempStr = bufferedReader.readLine())!=null){ //读取文件
            sb.append(tempStr);
        }

        creatFold(dir);
        File file = new File(dir,fileName);
        createFile(file);
        FileOutputStream out = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(sb.toString()); //写入文件

        writer.flush();
        in.close();
        reader.close();
        bufferedReader.close();
        out.close();
        writer.close();
        return file.getAbsolutePath();
    }



    private void createFile(File file) throws IOException {
        file.createNewFile();
    }

    public void creatFold(String path){
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
    }

//    public String mysqlHome = "e:\\MySQL\\bin\\mysqldump -h localhost -uroot -p123 db_name";

}
